﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Collections.Specialized;
using System.IO;

namespace LuShanTea.Web.Common
{
    public static class MVCHelper
    {
        public static string GetValidMsg(ModelStateDictionary modelState)// 有 两 个ModelStateDictionary 类，别弄混乱了，要用 using System.Web.Mvc; 下的 
        {
            StringBuilder sb = new StringBuilder();
            foreach (var ms in modelState.Values)
            {
                foreach (var modelError in ms.Errors)
                {
                    sb.AppendLine(modelError.ErrorMessage);
                }
            }
            return sb.ToString();
        }


        public static string ToQueryString(NameValueCollection queryString)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < queryString.Keys.Count; i++)
            {
                string key = queryString.Keys[i];
                sb.Append(key).Append("=").Append(Uri.EscapeDataString(queryString[key]));
                if (i != queryString.Keys.Count - 1)
                {
                    sb.Append("&");
                }
            }
            return sb.ToString();
        }

        public static string UpdateQueryString(NameValueCollection queryString, string name, string value)
        {     //拷贝一份，不影响本来的 
            NameValueCollection newNVC = new NameValueCollection(queryString);

            if (newNVC.AllKeys.Contains(name))
            {
                newNVC[name] = Convert.ToString(value);
            }
            else
            {
                newNVC.Add(name, Convert.ToString(value));
            }
            return ToQueryString(newNVC);
        }

        public static string RemoveQueryString(NameValueCollection queryString, string name)
        {
            NameValueCollection newNVC = new NameValueCollection(queryString);
            newNVC.Remove(name);
            return ToQueryString(newNVC);
        }

        public static string RenderViewToString(ControllerContext context, string viewPath, object model = null)
        {
            ViewEngineResult viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
            if (viewEngineResult == null)
                throw new FileNotFoundException("View" + viewPath + "cannot be found.");
            var view = viewEngineResult.View;
            context.Controller.ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
                view.Render(ctx, sw);
                return sw.ToString();
            }
        }
    }
}
